<template>
  <div class="compact-container">
    <!-- Compact search row with buttons on the right -->
    <div class="search-row">
      <span class="search-label">客户名称（编码）：</span>
      <el-input v-model="customerName" size="small" class="search-input" />
      <span class="search-label">联系电话：</span>
      <el-input v-model="customerPhone" size="small" class="search-input" />
      <el-button type="primary" size="small" @click="query">查询</el-button>
      <el-button size="small" @click="reset">重置</el-button>
      <div class="flex-grow"></div>
      <el-button type="primary" size="small" @click="exportToExcel">导出</el-button>
      <el-button type="primary" size="small" @click="addEdit">添加</el-button>
    </div>

    <el-divider style="margin: 6px 0" />

    <!-- Compact table area -->
    <div class="table-wrapper">
      <el-table :data="tableData" border style="width: 100%" :cell-style="{ textAlign: 'center', padding: '4px 0' }"
        :header-cell-style="{
          textAlign: 'center',
          background: '#f5f7fa',
          fontWeight: 'bold',
          position: 'sticky',
          top: 0,
          padding: '4px 0',
          height: '36px'
        }" ref="customerTable">
        <el-table-column fixed width="180px" prop="customer_code" label="客户编号">
          <template #default="scope">
            <el-link type="primary" @click="infoPage(scope.row.customer_code)">
              {{ scope.row.customer_code }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="customer_name" label="客户名称" width="180px" />
        <el-table-column prop="contacts_phone" label="联系电话" width="180px" />
        <el-table-column prop="customer_status" label="客户状态" width="150px">
          <template #default="scope">
            {{ statusValue(scope.row.customer_status) }}
          </template>
        </el-table-column>
        <el-table-column prop="customer_level" label="客户级别" width="180px">
          <template #default="scope">
            <el-rate :model-value="scope.row.customer_level" :colors="colors" disabled size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="customer_industry" label="所属行业" width="150px">
          <template #default="scope">
            {{ industryValue(scope.row.customer_industry) }}
          </template>
        </el-table-column>
        <el-table-column prop="customer_address" label="客户地址" width="180px" />
        <el-table-column prop="create_by" label="创建人" />
        <el-table-column prop="create_time" label="创建时间" width="190px">
          <template #default="scope">
            {{ scope.row.create_time.replace('T', ' ') }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180px">
          <template #default="scope">
            <div class="action-group">
              <el-button size="small" @click="handleEdit(scope.row.customer_code)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- Centered pagination -->
      <div class="pagination-center">
        <el-pagination small v-model:current-page="currentPage" v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]" :background="true" layout="total, sizes, prev, pager, next, jumper"
          :total="pageCount" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, markRaw, toRaw } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { useStore } from 'vuex'

export default {
  setup() {
    const tableData = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const pageCount = ref(0)
    const customerName = ref("")
    const customerPhone = ref("")
    const industryOptios = ref([])
    const statusOptios = ref([])
    const router = useRouter()
    const store = useStore()
    const customerTable = ref(null)
    const colors = ref(['#99A9BF', '#F7BA2A', '#FF9900'])

    onMounted(() => {
      getStatus()
      getIndustry()
      fill()
      count()
    })

    function fill() {
      axios.get("http://localhost:5181/api/Sinv_Customer/GetSinv_Customer", {
        params: {
          currentPage: currentPage.value,
          pageSize: pageSize.value,
          name: customerName.value,
          phone: customerPhone.value
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        tableData.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function count() {
      axios.get("http://localhost:5181/api/Sinv_Customer/GetSinv_CustomerCount", {
        params: {
          name: customerName.value,
          phone: customerPhone.value
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        pageCount.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function getIndustry() {
      axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
          dict_type: "customer_industry"
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        industryOptios.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function industryValue(row) {
      if (!row) return "无"
      const parentDept = industryOptios.value.find((industry) => industry.dict_value == row)
      return parentDept ? parentDept.dict_label : "无"
    }

    function getStatus() {
      axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
          dict_type: "customer_status"
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        statusOptios.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function statusValue(row) {
      if (!row) return "无"
      const parentDept = statusOptios.value.find((status) => status.dict_value == row)
      return parentDept ? parentDept.dict_label : "无"
    }

    function handleSizeChange(val) {
      pageSize.value = val
      fill()
    }

    function handleCurrentChange(val) {
      currentPage.value = val
      fill()
    }

    function query() {
      fill()
      count()
    }

    function reset() {
      customerName.value = ""
      customerPhone.value = ""
      query()
    }

    function handleDelete(row) {
      ElMessageBox.confirm(
        '此操作将删除'+row.customer_name+'客户信息，是否继续？',
        '警告',
        {
          type: 'warning',
          icon: markRaw(Delete),
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }
      )
        .then(() => {
          const loadingInstance = ElLoading.service({
            lock: true,
            text: '正在删除中...',
            background: 'rgba(0, 0, 0, 0.7)',
          });
          axios.put("http://localhost:5181/api/Sinv_Customer/Sinv_CustomerDel", {
            customer_id: row.customer_id,
            del_flag: '1'
          }, {
            headers: {
              authorization: `Bearer ${localStorage.getItem('token')}`
            }
          }).then((result) => {
            if (result.data > 0) {
              ElMessage.success('删除成功！')
              fill()
              count()
            }
          }).catch((err) => {
            console.error(err)
          }).finally(() => {
            loadingInstance.close();
          })
        })
        .catch(() => {
          ElMessage.info('已取消删除')
        })
    }

    function addEdit() {
      router.push("/main/Sinv/CustomerAdd")
    }

    function handleEdit(row) {
      store.commit("customerCode", row)
      router.push("/main/Sinv/CustomerUpdate")
    }

    function infoPage(row) {
      store.commit("customerCode", row)
      router.push("/main/Sinv/CustomerInfo")
    }

    function getTableHeaders() {
      if (customerTable.value) {
        const filteredColumns = customerTable.value.columns.filter(column => {
          return column.label !== '操作'
        })
        const headers = filteredColumns.map(column => column.label)
        return headers
      }
      return []
    }

    const exportToExcel = async () => {
      const headers = getTableHeaders()
      const row = toRaw(tableData.value)
      const headerMap = {
        '客户编号': 'customer_code',
        '客户名称': "customer_name",
        '联系电话': 'contacts_phone',
        '客户状态': 'customer_status',
        '客户级别': 'customer_level',
        '所属行业': 'customer_industry',
        '客户地址': 'customer_address',
        '创建人': 'create_by',
        '创建时间': 'create_time',
      }

      const rowDataArray = row.map(item => {
        return headers.map(header => {
          const propName = headerMap[header]
          if (propName === "customer_industry") {
            return industryValue(item[propName])
          } else if (propName === "customer_status") {
            return statusValue(item[propName])
          } else if (propName === "customer_level") {
            return item[propName] + "星"
          } else {
            return item[propName]
          }
        })
      })

      try {
        const response = await axios.post('http://localhost:5181/api/SystemHome/ExportExcel', {
          headers: headers,
          rows: rowDataArray,
          title: "客户信息"
        }, {
          responseType: 'blob'
        })

        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', '客户信息.xlsx')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      } catch (error) {
        console.error('导出 Excel 失败:', error)
      }
    }

    return {
      tableData, currentPage, pageSize, pageCount, customerName, customerPhone,
      industryOptios, industryValue, statusValue, colors, customerTable,
      handleSizeChange, handleCurrentChange, query, reset, handleDelete,
      addEdit, handleEdit, infoPage, exportToExcel
    }
  }
}
</script>

<style scoped>
.compact-container {
  padding: 10px;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 6px;
  margin-top: -40px;
}

.search-label {
  white-space: nowrap;
  font-size: 13px;
}

.search-input {
  width: 160px !important;
}

.flex-grow {
  flex-grow: 1;
}

.table-wrapper {
  margin-top: 6px;
}

.pagination-center {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.action-group {
  display: flex;
  justify-content: center;
  gap: 4px;
}

:deep(.el-table__row) {
  height: 36px !important;
}

:deep(.el-table th.el-table__cell) {
  height: 36px !important;
}

:deep(.el-button--small) {
  padding: 5px 8px;
  height: 24px;
}

:deep(.el-rate) {
  --el-rate-icon-size: 14px;
}
</style>